//
//  ServersyncClass.m
//  A One POS
//
//  Created by AonePOS on 24/09/13.
//  Copyright (c) 2013 AonePOS. All rights reserved.
//

#import "ServersyncClass.h"
#import "general data.h"
#import "AppDelegate.h"


@implementation ServersyncClass
{
    general_data *generalDataObject;
}
NSURLConnection *BckupConnection,*PendimgConnection;
NSMutableData *BackupResponseData,*PendingResponseData;
NSURLConnection *logoutConnection,*loginConnection,*InvConnection;
NSMutableData *ResponseData,*loginResponseData,*InvResponseData;


-(void)ServerSyncronizationMethod
{
   generalDataObject=[general_data new];
    [generalDataObject GetuserDataVariablesMethod];
    
      NSString *localSystemTime,*PreviousServerSynTime;
    
     NSString *querySQL = [NSString stringWithFormat:@"SELECT last_server_update_time FROM miscellaneous"];
    NSMutableArray *misArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:misArray];
      //[self PendingClearMethod];
  

    if ([misArray count]>0)
    {
        NSString *lasttime;
        for (NSDictionary *Dict in misArray)
        {
           lasttime=[Dict objectForKey:@"last_server_update_time"];
           
        }
        if ([lasttime length]>0)
        {
             PreviousServerSynTime=lasttime;
        }
        else
        {
            PreviousServerSynTime=@"previousday";
            
        }
    }
    localSystemTime=[generalDataObject Datestring];
    
    //NSLog(@"server time %@",PreviousServerSynTime);
    //NSLog(@"local time%@",localSystemTime);
    
    if ([PreviousServerSynTime isEqualToString:@"previousday"])
    {
        
        if ([[generalDataObject OriginalbaseURLstr] length]>0)
        {
            [self PendingClearMethod];
            
        NSString *string=[NSString stringWithFormat:@"%@backup.php?Currentsystemtime=%@&previous-sync-time=%@&sessionid=%@&previousday=true",[[generalDataObject OriginalbaseURLstr]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[PreviousServerSynTime stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject SessionID]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
    
        [self BackUpDataMethod:string];
        }
    }
    else
    {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date1 = [dateFormat dateFromString:localSystemTime];
       NSDate *date2=[dateFormat dateFromString:PreviousServerSynTime];
    
        //NSLog(@"date1%@,Date2 %@",date1,date2);
        
      
        NSTimeInterval diff = [date1 timeIntervalSinceDate:date2];
       
       
        //NSLog(@" time difference %f",diff);
        if(diff<30000)
        {
            
          

        }else{
          
            
            if ([[generalDataObject OriginalbaseURLstr] length]>0)
            {
        
            [self PendingClearMethod];
            
            
            NSString *string=[NSString stringWithFormat:@"%@backup.php?Currentsystemtime=%@&previous-sync-time=%@&sessionid=%@&previousday=false",[[generalDataObject OriginalbaseURLstr]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[PreviousServerSynTime stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject genRandStringLength:20]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            
            [self BackUpDataMethod:string];
            }
            
            
         
        }
    }
    
}
-(void)BackUpDataMethod:(NSString *)str
{
    //NSLog(@"%@",str);
    
    NSURL *url=[NSURL URLWithString:str];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //NSLog(@"%@",url);
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    
     BckupConnection = [[NSURLConnection alloc]
                                    initWithRequest:request
                                    delegate:self startImmediately:NO];
    
    [BckupConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                          forMode:NSDefaultRunLoopMode];
    
    [BckupConnection start];
    
    
}
-(void)PendingClearMethod
{
   
      NSMutableArray  *QuerytypesArray=[[NSMutableArray alloc]init];
        NSMutableArray  *TablenamesArray=[[NSMutableArray alloc]init];
        NSMutableArray  *FieldsArray=[[NSMutableArray alloc]init];
    
    int offset=0;
  
    
    NSString *String;
    
    NSString *selectsql2=[NSString stringWithFormat:@"SELECT   query_type,table_name,parameters FROM pending_queries  where user_id='%@' ORDER BY current_time='%@' ASC ",[generalDataObject userID],[generalDataObject Datestring]];
    //NSLog(@"pending query %@",selectsql2);
    NSMutableArray *pendingsArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:selectsql2 resultsArray:pendingsArray];
    
        int count=[pendingsArray count];
        
    for (;offset<count; )
    {
  
        NSString *selectsql=[NSString stringWithFormat:@"SELECT  query_type,table_name,parameters FROM pending_queries  where user_id='%@' ORDER BY current_time='%@' ASC limit 100 offset %d",[generalDataObject userID],[generalDataObject Datestring],offset];
        
        NSMutableArray *pendingsArray=[[NSMutableArray alloc]init];
       
        
        if(count<100)
        {
			offset = offset+count;
		}
        else
        {
			offset = offset+100;
			count = count - offset;
		}
        
        if ([selectsql length]>0)
        {
            [[DataBaseManager dataBaseManager]execute:selectsql2 resultsArray:pendingsArray];
        }
   
        
    if ([pendingsArray count]>0)
    {
      
        for (NSDictionary *Dict in pendingsArray)
        {
           [QuerytypesArray addObject:[Dict objectForKey:@"query_type"]];
            [TablenamesArray addObject:[Dict objectForKey:@"table_name"]];
            [FieldsArray addObject:[Dict objectForKey:@"parameters"]];
            
        }
        for (int i=0; i<[QuerytypesArray count]; i++)
        {
            NSString *Querytype=[QuerytypesArray objectAtIndex:i];
             NSString *tablename=[TablenamesArray objectAtIndex:i];
            NSString *parameters=[FieldsArray objectAtIndex:i];
            if ([Querytype isEqualToString:@"createadminprofile"])
            {
                String=[NSString stringWithFormat:@"%@create-admin-profile.php?defaultusername=01&defaultpassword=admin&data=%@",[generalDataObject OriginalbaseURLstr],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                //NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                
                
                PendimgConnection = [[NSURLConnection alloc]
                                     initWithRequest:request
                                     delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                             forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];
                
            }
            if ([Querytype isEqualToString:@"login"])
            {
                
               String=[NSString stringWithFormat:@"%@user-login.php?%@",[generalDataObject OriginalbaseURLstr],parameters];
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
               // //NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                
                
                PendimgConnection = [[NSURLConnection alloc]
                                     initWithRequest:request
                                     delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                             forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];
                
                
            }
            if ([Querytype isEqualToString:@"logout"])
            {
                String=[NSString stringWithFormat:@"%@user-login.php?%@",[generalDataObject OriginalbaseURLstr],parameters];
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                ////NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                
                
                PendimgConnection = [[NSURLConnection alloc]
                                     initWithRequest:request
                                     delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                             forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];
                
            }
            if ([Querytype isEqualToString:@"INSERT"])
            {
               
                String=[NSString stringWithFormat:@"%@saveinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&data=%@",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
               // //NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                
            
                PendimgConnection = [[NSURLConnection alloc]
                                   initWithRequest:request
                                   delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                           forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];

            }
            if ([Querytype isEqualToString:@"UPDATE"])
            {
                
                 String=[NSString stringWithFormat:@"%@saveinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&data=%@&update=true",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
               // //NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                
                
                PendimgConnection = [[NSURLConnection alloc]
                                     initWithRequest:request
                                     delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                             forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];

            }
            if ([Querytype isEqualToString:@"DELETE"])
            {
                 String=[NSString stringWithFormat:@"%@deleteinfo.php?tablename=%@&systemtime=%@&userid=%@&sessionid=%@&unique_ids=%@",[generalDataObject OriginalbaseURLstr],[tablename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                NSURL *url=[NSURL URLWithString:String];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
                ////NSLog(@"%@",url);
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                
                PendimgConnection = [[NSURLConnection alloc]
                                     initWithRequest:request
                                     delegate:self startImmediately:NO];
                
                [PendimgConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                             forMode:NSDefaultRunLoopMode];
                [PendimgConnection start];

            }
            if ([Querytype isEqualToString:@"edit"])
            {
                
              NSString   *bodyString  = [NSString stringWithFormat:@"query-string=%@",[parameters stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                
                NSString *urlstring=[NSString stringWithFormat:@"%@execute.php?",[generalDataObject OriginalbaseURLstr]];
                
                /////NSLog(@"%@",bodyString);
               // //NSLog(@"%@",urlstring);
                
                NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]];
                
                [request setTimeoutInterval:20.0];
                
                NSData *requestData = [NSData dataWithBytes:[bodyString UTF8String] length:[bodyString length]];
                
                [request setHTTPMethod:@"POST"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                
                [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                [request setValue:[NSString stringWithFormat:@"%d", [bodyString length]] forHTTPHeaderField:@"Content-Length"];
                [request setHTTPBody:requestData];
                ////NSLog(@"%@",request);
                
                InvConnection = [NSURLConnection connectionWithRequest:request delegate:self];
                
                [InvConnection start];
                
            }

        }
     }
    }
}
-(void)LogoutMethod
{
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  
    
    NSString *querySQL = [NSString stringWithFormat: @"SELECT login_time FROM login_logout_table where sessioniduniqueval='%@'",appDelegate.loginSessionID];
    
    NSMutableArray *lohinArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL resultsArray:lohinArray];
    
   // NSLog(@"%@",querySQL);
    
    NSString *logintime;
    for (NSDictionary *myDict in lohinArray)
    {
        logintime=[myDict objectForKey:@"login_time"];
    }
   // //NSLog(@"login time %@",logintime);
    
    NSDate *aDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *datestr;
    datestr=[formatter stringFromDate:aDate];

    
    NSString *logouttime=datestr;
  //  //NSLog(@"logout time %@",logouttime);
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date1 = [dateFormat dateFromString:logouttime];
    NSDate *date2=[dateFormat dateFromString:logintime];
    
  //  //NSLog(@"date1%@,Date2 %@",date1,date2);
    
    
    NSTimeInterval diff = [date1 timeIntervalSinceDate:date2];
    
    
    
    double secondsInAnHour = 3600;
    NSInteger hoursBetweenDates = diff / secondsInAnHour;
    NSString *hourTime=@"";
    NSString *hours=@"";
    hourTime=[NSString stringWithFormat:@"%0.2ld",(long)hoursBetweenDates];
    hoursBetweenDates=hoursBetweenDates/60;
    
    hours=[NSString stringWithFormat:@"%0.2ld",(long)hoursBetweenDates];
    
    
    NSString *updateSQL =@"UPDATE login_logout_table SET logout_time=?,diff_minutes=?,diff_hours=? WHERE sessioniduniqueval=?";
    
    NSMutableArray *updateArray=[[NSMutableArray alloc]initWithObjects:logouttime,hours,hourTime,[generalDataObject loginSessionID], nil];
    [[DataBaseManager dataBaseManager]executeRecordsWithQuery:updateSQL withArguments:updateArray];
    
    NSString *querySQL2 = [NSString stringWithFormat: @"SELECT login_employee_name, login_employee_id,login_time,logout_time,diff_minutes,diff_hours,wages,sessioniduniqueval,unique_id,created_timestamp,modified_timestamp,server_local FROM login_logout_table where sessioniduniqueval='%@'",appDelegate.loginSessionID];
    
    NSMutableArray *loginArray=[[NSMutableArray alloc]init];
    [[DataBaseManager dataBaseManager]execute:querySQL2 resultsArray:loginArray];
    
    NSMutableDictionary *CategoryDict=[[NSMutableDictionary alloc]init];
    [CategoryDict setObject:loginArray forKey:@"fields"];
    NSDictionary *jsonDict = [NSDictionary dictionaryWithDictionary:CategoryDict];
    
    NSError *err;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&err];
    
    NSString *str=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
   // //NSLog(@"%@", str);
    
    if(![generalDataObject connectedToInternet])
    {
        NSString *insertSQL =@"insert into pending_queries (query_type,user_id,page_url,parameters,table_name,current_time) values(?,?,?,?,?,?)";
        NSMutableArray *pendingArray=[[NSMutableArray alloc]initWithObjects:@"UPDATE",[generalDataObject userID],@"saveinfo.php?",str,@"login_logout_table",[generalDataObject Datestring], nil];
        
        [[DataBaseManager dataBaseManager] executeRecordsWithQuery:insertSQL withArguments:pendingArray];
    }
    else if([generalDataObject connectedToInternet])
    {
        
        if ([[generalDataObject OriginalbaseURLstr] length]>0)
        {
            
            ////NSLog(@"%@",str);
            NSString *string=[NSString stringWithFormat:@"%@saveinfo.php?tablename=login_logout_table&systemtime=%@&userid=%@&sessionid=%@&data=%@&update=true",[generalDataObject OriginalbaseURLstr],[[generalDataObject Datestring] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[generalDataObject userID],[generalDataObject genRandStringLength:20],[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            
           // //NSLog(@"%@",str);
            
            NSURL *url=[NSURL URLWithString:string];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
           // //NSLog(@"%@",url);
            
            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            
            
            
            loginConnection = [NSURLConnection connectionWithRequest:request delegate:self];
            
            [loginConnection start];
            
        }
    }
    
    
    
    //logout
    
    if(![generalDataObject connectedToInternet])
    {
       
        NSString *insertSQL =@"insert into pending_queries (query_type,user_id,page_url,parameters,table_name,current_time) values(?,?,?,?,?,?)";
        
        NSMutableArray *pendingArray=[[NSMutableArray alloc]initWithObjects:@"logout",[generalDataObject userID],@"%@user-login.php?",[NSString stringWithFormat:@"username=%@&sessionid=%@&deviceid=%@&logout=true",[generalDataObject userID],[generalDataObject SessionID],[generalDataObject deviceID]],@"",[generalDataObject Datestring], nil];
        
        [[DataBaseManager dataBaseManager] executeRecordsWithQuery:insertSQL withArguments:pendingArray];
        
        
    }
    else if([generalDataObject connectedToInternet])
    {
        
        if ([[generalDataObject OriginalbaseURLstr] length]>0)
        {
            
            NSString *urlstring=[NSString stringWithFormat:@"%@user-login.php?username=%@&sessionid=%@&deviceid=%@&logout=true",[generalDataObject OriginalbaseURLstr],[generalDataObject userID],[generalDataObject SessionID],[generalDataObject deviceID]];
            ////NSLog(@"logout url is %@",urlstring);
            NSURLRequest *request = [NSURLRequest requestWithURL:
                                     [NSURL URLWithString:urlstring]];
            logoutConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
        }
        
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
    if (connection == BckupConnection){
        BackupResponseData = [[NSMutableData alloc] init];
    }else if (connection == PendimgConnection){
        PendingResponseData = [[NSMutableData alloc] init];
    }else if (connection==logoutConnection){
        ResponseData = [[NSMutableData alloc] init];
    }else if (connection==loginConnection){
        loginResponseData = [[NSMutableData alloc] init];
    }else if (connection==InvConnection){
        InvResponseData = [[NSMutableData alloc] init];
    }

    
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    if (connection == BckupConnection){
        [BackupResponseData appendData:data];
    }else if (connection == PendimgConnection){
        [PendingResponseData appendData:data];
    }else if (connection==logoutConnection){
        [ResponseData appendData:data];
    }else if (connection==loginConnection){
        [loginResponseData appendData:data];
    }else if (connection==InvConnection){
        [InvResponseData appendData:data];
    }

    
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    
    if (connection==InvConnection){
        NSString *responseStr = [[NSString alloc] initWithBytes:[InvResponseData mutableBytes] length:[InvResponseData length] encoding:NSUTF8StringEncoding];
        //NSLog(@"%@",responseStr);
        NSError *error;
        NSMutableDictionary *dataDict;
       dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"repose  data %@",dataDict);
        
        
        NSString *Servertime=[[dataDict objectForKey:@"response"] objectForKey:@"server-time"];
       // NSLog(@"%@",Servertime);
        NSString *selectQuery=[NSString stringWithFormat:@"select selected_store, local_time,pageurl,last_server_update_time from miscellaneous"];
        NSMutableArray *mislaneousArray=[[NSMutableArray alloc]init];
        [[DataBaseManager dataBaseManager]execute:selectQuery resultsArray:mislaneousArray];
        
        if ([mislaneousArray count]>0){
            NSString *updateSQL =@"UPDATE miscellaneous SET last_server_update_time=?";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:Servertime, nil];
            [[DataBaseManager dataBaseManager] executeRecordsWithQuery:updateSQL withArguments:misUpdatearray];
        }else{
            NSString *insertSQL =@"insert into miscellaneous (selected_store,local_time,pageurl,last_server_update_time) values(?,?,?,?)";
            
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:@"Store1",[generalDataObject Datestring],[generalDataObject OriginalbaseURLstr],Servertime, nil];
            
        [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertSQL withArguments:misUpdatearray];
        }
        
        
        
    }else if (connection==logoutConnection){
        NSString *responseStr = [[NSString alloc] initWithBytes:[ResponseData mutableBytes] length:[ResponseData length] encoding:NSUTF8StringEncoding];
        NSError *error;
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        
         NSMutableDictionary *dataDict;
        dataDict=[[NSMutableDictionary alloc]init];
        
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        
        NSDictionary *Dict=[dataDict objectForKey:@"response"];
        NSString *logout=[Dict objectForKey:@"logout"];
        int logoutvalue=[logout intValue];
        if (logoutvalue==1)
        {
            
        }
        //jsondataArray=[dataDict objectForKey:@"response"];
        //NSLog(@"logout data is %@",dataDict);
        
    }else if (connection == BckupConnection){
        
        NSString *responseStr = [[NSString alloc] initWithBytes:[BackupResponseData mutableBytes] length:[BackupResponseData length] encoding:NSUTF8StringEncoding];
        
        NSError *error;
        
        NSMutableDictionary *dataDict;
        dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
       // NSLog(@"back up data %@",dataDict);
        
        NSMutableArray *deleteArray=[dataDict objectForKey:@"queries-array"];
        // NSMutableArray *insertsArray=[dataDict objectForKey:@"insert-queries"];
        NSMutableArray *deletesArray=[[NSMutableArray alloc]init];
        for (int i=0; i<[deleteArray count]; i++)
        {
            NSString *foo=[deleteArray objectAtIndex:i];
            NSString* bar = [foo stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* deletestr = [bar stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletestr withArguments:deletesArray];
            
        }
        NSString *nexturl=[dataDict objectForKey:@"next-url"];
        if([nexturl isKindOfClass:[NSNull class]])
        {
            //NSLog(@"next url null");
        }
        else
        {
            [self BackUpDataMethod:nexturl];
            
        }
        
        //NSString *Servertime=[[dataDict objectForKey:@"response"] objectForKey:@"server-time"];
        
        NSString *selectQuery=[NSString stringWithFormat:@"select selected_store, local_time,pageurl,last_server_update_time from miscellaneous"];
        NSMutableArray *mislaneousArray=[[NSMutableArray alloc]init];
        [[DataBaseManager dataBaseManager]execute:selectQuery resultsArray:mislaneousArray];
        
        if ([mislaneousArray count]>0){
            NSString *updateSQL =@"UPDATE miscellaneous SET last_server_update_time=?";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:[generalDataObject getsystemDatetime], nil];
        [[DataBaseManager dataBaseManager] executeRecordsWithQuery:updateSQL withArguments:misUpdatearray];
            
        }else{
            NSString *insertSQL =@"insert into miscellaneous (selected_store,local_time,pageurl,last_server_update_time) values(?,?,?,?)";
            NSMutableArray *misUpdatearray=[[NSMutableArray alloc]initWithObjects:@"Store1",[generalDataObject getsystemDatetime],[generalDataObject OriginalbaseURLstr],[generalDataObject getsystemDatetime], nil];
         [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertSQL withArguments:misUpdatearray];
        }
        
    }else if (connection == PendimgConnection){
        
        NSString *responseStr = [[NSString alloc] initWithBytes:[PendingResponseData mutableBytes] length:[PendingResponseData length] encoding:NSUTF8StringEncoding];
        
        NSError *error;
         NSMutableDictionary *dataDict;
        dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"Pending query data %@",dataDict);
        
        NSMutableArray *deleteArray=[dataDict objectForKey:@"delete-queries"];
        NSMutableArray *insertsArray=[dataDict objectForKey:@"insert-queries"];
        
        NSMutableArray *deletesArray=[[NSMutableArray alloc] init];
        for (int i=0; i<[deleteArray count]; i++)
        {
            NSString *foo=[deleteArray objectAtIndex:i];
            NSString* bar = [foo stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* deletestr = [bar stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletestr withArguments:deletesArray];
            
            NSString *foo2=[insertsArray objectAtIndex:i];
            NSString* bar2 = [foo2 stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* insertstr = [bar2 stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertstr withArguments:deletesArray];
        }
        
        NSString *Deletependingquery=[NSString stringWithFormat:@"DELETE FROM pending_queries "];
        [[DataBaseManager dataBaseManager]executeRecordsWithQuery:Deletependingquery withArguments:deletesArray];
        
    }else if (connection == loginConnection){
        
        NSString *responseStr = [[NSString alloc] initWithBytes:[loginResponseData mutableBytes] length:[loginResponseData length] encoding:NSUTF8StringEncoding];
        
        NSError *error;
         NSMutableDictionary *dataDict=[[NSMutableDictionary alloc] init];
        NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
        
        dataDict =[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        //NSLog(@"%@",dataDict);
        
        NSMutableArray *deleteArray=[dataDict objectForKey:@"delete-queries"];
        NSMutableArray *insertsArray=[dataDict objectForKey:@"insert-queries"];
        
        NSMutableArray *deletesArray;
        for (int i=0; i<[deleteArray count]; i++)
        {
            NSString *foo=[deleteArray objectAtIndex:i];
            NSString* bar = [foo stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* deletestr = [bar stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:deletestr withArguments:deletesArray];
            
            NSString *foo2=[insertsArray objectAtIndex:i];
            NSString* bar2 = [foo2 stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
            NSString* insertstr = [bar2 stringByReplacingOccurrencesOfString:@"\\\"" withString:@"'"];
            
            [[DataBaseManager dataBaseManager]executeRecordsWithQuery:insertstr withArguments:deletesArray];
        }
        
        
        
    }
}


@end
